package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.CreadChapterBookBean;
import com.ljfiction.book.Baner.CreatBaocunBean;
import com.ljfiction.book.Baner.CreatBeijingBean;
import com.ljfiction.book.Baner.NextVolumBean;
import com.ljfiction.book.Baner.SketchBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.TocunDialog;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SystemToolUtils;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.CreatChapterSettingManager;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.SoftKeyBoardListener;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class
ArticleActivity extends BaseActivity {

    @BindView(R.id.back_article)
    ImageView backArticle;
    @BindView(R.id.textnum_article)
    TextView textnumArticle;
    @BindView(R.id.ok_article)
    TextView okArticle;
    @BindView(R.id.volume0k)
    TextView volume0k;
    @BindView(R.id.volume_article)
    LinearLayout volumeArticle;
    @BindView(R.id.zhangjiename)
    ContainsEmojiEditText zhangjiename;
    @BindView(R.id.zhangjietext)
    ContainsEmojiEditText zhangjietext;

    @BindView(R.id.yijianpaiban)
    ImageView yijianpaiban;
    @BindView(R.id.toleft)
    ImageView toleft;
    @BindView(R.id.toright)
    ImageView toright;
    @BindView(R.id.set_creat)
    ImageView setCreat;
    @BindView(R.id.creat_top)
    LinearLayout creatTop;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.back_bg_image)
    ImageView backBgImage;
    @BindView(R.id.douhaorecycle)
    RecyclerView douhaorecycle;
    @BindView(R.id.douhaoimage)
    ImageView douhaoimage;
    @BindView(R.id.douhaolayout)
    RelativeLayout douhaolayout;
    @BindView(R.id.view4)
    View view4;
    @BindView(R.id.view3)
    View view3;
    @BindView(R.id.scrollview_arti)
    ScrollView scrollviewArti;
    @BindView(R.id.scroolrelative)
    RelativeLayout scroolrelative;
    @BindView(R.id.yijianbaocun)
    ImageView yijianbaocun;
    @BindView(R.id.auhorSay_addimage)
    ImageView auhorSayAddimage;
    @BindView(R.id.auhorSay_text)
    TextView auhorSayText;
    @BindView(R.id.authersay_creat)
    CardView authersayCreat;


    private String bookId;
    private String bookName;
    private int vip = 0;//是否发布VIP，0是非VIP，1是VIP
    private int isvip;//书是否VIP，0是非VIP，1是VIP
    private String volumId = "", volumName = "请选择";
    private Intent intent;//选择卷
    private Intent intent1;//发布
    private SketchBean.DataBean.ResultListBean bookDataBean;
    private int isCaogaoCome;//1是从草稿箱进来的，0不是
    private NoBackgLodDialog noBackgLodDialog;
    private NextVolumBean nextvolum;
    private PopupWindow popupWindowset;
    private ViewHolder viewHolder;
    private CreatBeijingBean beijingBean;
    private int beijingposition = 0;//背景所属坐标
    private int isNeight = 0;//是否黑夜，0是白天
    private int seekposition;//亮度
    private int zitiposition;//字大小
    private Handler handler;
    private CreatBaocunBean creatBaocunBean;
    private Runnable runnable;
    private List<String> douhaoList = new ArrayList<>();
    private boolean zhangjianameisfocus = false, zhangjietextisfocus = false;
    private ArrayList<String> textList = new ArrayList<>();//保存上下内容
    private int textPosition = -1;//显示的内容下表
    private boolean isnochange = false;//是否编写改变的内容
    private String authorSay = "作者什么都没说";
    private TocunDialog tocunDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        ButterKnife.bind(this);
        beijingBean = new CreatBeijingBean();
        beijingposition = CreatChapterSettingManager.getInstance().getCreatBeijingcolor();
        isNeight = CreatChapterSettingManager.getInstance().getIsCreatNightDay();
        AppUtils.init(this);
        //SoftHideKeyBoardUtil.assistActivity(this);
        setBeijingAll();
        seekposition = CreatChapterSettingManager.getInstance().getCreatSeekposition() == 0 ? ScreenUtils.getScreenBrightness() : CreatChapterSettingManager.getInstance().getCreatSeekposition();
        zitiposition = CreatChapterSettingManager.getInstance().getCreatZitiSeekposition();
        zhangjietext.setTextSize(12 + zitiposition);
        isCaogaoCome = getIntent().getIntExtra("isCaogao", 0);
        if (isCaogaoCome == 1) {
            bookDataBean = (SketchBean.DataBean.ResultListBean) getIntent().getSerializableExtra("bookData");
            bookId = String.valueOf(bookDataBean.getBookId());
            bookName = bookDataBean.getBookTitle();
            volume0k.setText(bookDataBean.getVolumeName());
            volumId = String.valueOf(bookDataBean.getVolumeId());
            zhangjiename.setText(bookDataBean.getChapterTitle());
            zhangjietext.setText(StringTool.getCungaoChapter(bookDataBean.getChapterContent()));
            authorSay = bookDataBean.getAuthorWords();
            isvip = getIntent().getIntExtra("isvip", 0);
        } else {
            bookId = getIntent().getStringExtra("bookId");
            bookName = getIntent().getStringExtra("bookName");
            if (getIntent().getIntExtra("isvip", 0) > 1) {
                isvip = 1;
            } else {
                isvip = 0;
            }
            volumId = CreatChapterSettingManager.getInstance().getBookvolumId(bookId) + "";
            intvolume();
        }
        vip = isvip;
        intent = new Intent(this, SelectVolumActivity.class);
        intent1 = new Intent(this, CreadChapterOkActivity.class);
        intEnvent();
    }


    private void intvolume() {
        OkHttpUtils.post(HttpManager.IP + "/getLastVolume")

                .params("bookid", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Gson g = new Gson();
                            nextvolum = g.fromJson(s, NextVolumBean.class);
                            if (nextvolum.getReturnCode() == 200) {
                                volume0k.setText(nextvolum.getData().getVolumeName());
                                volumName = nextvolum.getData().getVolumeName();
                                volumId = String.valueOf(nextvolum.getData().getVolumeId());
                                CreatChapterSettingManager.getInstance().saveBookvolumId(bookId, Integer.valueOf(volumId));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intEnvent() {
        zhangjietext.setOnFocusChangeListener((v, hasFocus) -> {
            zhangjietextisfocus = hasFocus;
            toleftorright();
        });
        zhangjiename.setOnFocusChangeListener((v, hasFocus) -> zhangjianameisfocus = hasFocus);
        douhaoList.add("，");
        douhaoList.add("。");
        douhaoList.add("！");
        douhaoList.add("？");
        douhaoList.add("：");
        douhaoList.add("“”");
        douhaoList.add("、");
        douhaoList.add("；");
        BaseQuickAdapter adapter;
        douhaorecycle.setAdapter(adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.douhao_item, douhaoList) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.douhao_text, item);
            }
        });
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (zhangjietextisfocus) {
                zhangjietext.getText().insert(zhangjietext.getSelectionStart(), douhaoList.get(position));
                if (position == 5) {
                    zhangjietext.setSelection(zhangjietext.getSelectionStart() - 1);
                }

            }
            if (zhangjianameisfocus) {
                zhangjiename.getText().insert(zhangjiename.getSelectionStart(), douhaoList.get(position));
                if (position == 5) {
                    zhangjiename.setSelection(zhangjiename.getSelectionStart() - 1);
                }
            }
        });
        douhaorecycle.setLayoutManager(new GridLayoutManager(this, 8));
        douhaoimage.setOnClickListener(v -> SystemToolUtils.hideKeyBoard(ArticleActivity.this));
        //监听软键盘
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                douhaolayout.setVisibility(View.VISIBLE);
                authersayCreat.setVisibility(View.GONE);
                view3.setVisibility(View.GONE);
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                RelativeLayout.LayoutParams olp = (RelativeLayout.LayoutParams) douhaolayout.getLayoutParams();
                RelativeLayout.LayoutParams scrool = (RelativeLayout.LayoutParams) scrollviewArti.getLayoutParams();
                olp.setMargins(0, r.bottom - douhaolayout.getHeight(), 0, r.bottom);
                douhaolayout.setLayoutParams(olp);
                scrool.height = r.bottom - douhaolayout.getHeight() - ScreenUtils.getNum(ArticleActivity.this, 60 + zitiposition);
                scrollviewArti.setLayoutParams(scrool);
                toleftorright();
            }

            @Override
            public void keyBoardHide(int height) {
                douhaolayout.setVisibility(View.GONE);
                view3.setVisibility(View.VISIBLE);
                authersayCreat.setVisibility(View.VISIBLE);
                setCreat.setVisibility(View.VISIBLE);
                toleft.setVisibility(View.GONE);
                toright.setVisibility(View.GONE);
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                RelativeLayout.LayoutParams scrool = (RelativeLayout.LayoutParams) scrollviewArti.getLayoutParams();
                scrool.height = r.bottom + height - authersayCreat.getHeight();
                scrollviewArti.setLayoutParams(scrool);

            }
        });
        //定时保存
        handler = new Handler();
        runnable = () -> {
            if (!zhangjietext.getText().toString().equals("")) {
                toSaveContext();
            }
            handler.postDelayed(runnable, 60000);
        };
        handler.postDelayed(runnable, 60000);
        zhangjietext.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                //s:变化后的所有字符
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //s:变化前的所有字符； start:字符开始的位置； count:变化前的总字节数；after:变化后的字节数
                if (String.valueOf(s).length() >= 20000) {
                    showToast("字数不能大于20000哦");
                }
            }

            @SuppressLint("SetTextI18n")
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //S：变化后的所有字符；start：字符起始的位置；before: 变化之前的总字节数；count:变化后的字节数

                CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 0);
                textnumArticle.setText(StringTool.getChapterTextLength(zhangjietext.getText().toString()) + "字");

                if (!isnochange) {
                    if (s.toString().endsWith("\n")) {
                        zhangjietext.setText(zhangjietext.getText() + "        ");
                        zhangjietext.setSelection(zhangjietext.getText().length());
                    }
                    if (textPosition + 1 < textList.size()) {
                        for (int i = textPosition + 1; i < textList.size(); i++) {
                            textList.remove(i);
                        }
                    }
                    if (textList.size() < 10) {
                        textList.add(s.toString());
                        textPosition = textList.size() - 1;
                    } else {
                        textList.add(s.toString());
                        textList.remove(0);
                    }
                }
                isnochange = false;
                toleftorright();

            }
        });
    }

    //撤销和前进
    private void toleftorright() {
        if (zhangjietextisfocus) {
            setCreat.setVisibility(View.GONE);
            toleft.setVisibility(View.VISIBLE);
            toright.setVisibility(View.VISIBLE);
            if (textList.size() > textPosition + 1) {
                toright.setImageResource(beijingBean.getTorightlist().get(beijingposition));
            } else {
                toright.setImageResource(beijingBean.getNotorightlist().get(beijingposition));
            }
            if (textPosition > 0) {
                toleft.setImageResource(beijingBean.getToleftlist().get(beijingposition));
            } else {
                toleft.setImageResource(beijingBean.getNotoleftlist().get(beijingposition));
            }
        } else {
            toleft.setVisibility(View.GONE);
            toright.setVisibility(View.GONE);
            setCreat.setVisibility(View.VISIBLE);
        }

    }

    //本地保存
    private void toSaveContext() {
        if (creatBaocunBean == null) {
            creatBaocunBean = new CreatBaocunBean();
        }
        creatBaocunBean.setChapterContent(zhangjietext.getText().toString());
        creatBaocunBean.setVolumeId(volumId);
        creatBaocunBean.setTime(TimeTool.getThistime());
        creatBaocunBean.setBookName(bookName);
        creatBaocunBean.setBookWriterId(UserManageBean.userBean.getUserId());
        if (isCaogaoCome == 1) {
            creatBaocunBean.setChapterId(String.valueOf(bookDataBean.getId()));
        }
        if (zhangjiename.getText().toString().equals("")) {
            creatBaocunBean.setChapterTitle("无章节名称");
        } else {
            creatBaocunBean.setChapterTitle(zhangjiename.getText().toString());
        }

        creatBaocunBean.setIsfromCaogao(isCaogaoCome);
        creatBaocunBean.setAuthorSay(StringTool.getAuthorsayText(authorSay));
        CreatChapterSettingManager.getInstance().saveCreatobject(bookId, creatBaocunBean);

        Tool.zidongbancuntishi(this);
    }

    @OnClick({R.id.back_article, R.id.ok_article, R.id.volume_article, R.id.yijianpaiban, R.id.set_creat, R.id.toright, R.id.toleft, R.id.authersay_creat, R.id.yijianbaocun})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_article:
                if (!StringTool.isEmpty(zhangjietext.getText().toString())) {
                    if (volumId.equals("0")) {
                        showToast("请重新选择卷");
                        return;
                    }

                    isCungao(true);
                } else {
                    CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                    goBack();
                }
                break;
            case R.id.yijianbaocun:
                if (!StringTool.isEmpty(zhangjietext.getText().toString())) {
                    if (volumId.equals("0")) {
                        showToast("请重新选择卷");
                        return;
                    }

                    isCungao(true);
                } else {
                    showToast("章节内容不能为空");
                }
                break;

            case R.id.ok_article:
                isCungao(false);
                break;
            case R.id.volume_article:
                intent.putExtra("bookId", bookId);
                intent.putExtra("bookName", bookName);
                startActivityForResult(intent, 1);
                break;
            case R.id.yijianpaiban:
                zhangjietext.setText(StringTool.getPaibanChapter(zhangjietext.getText().toString()));
                showToast("一键排版成功");
                zhangjietext.setSelection(zhangjietext.getText().length());
                break;
            case R.id.set_creat:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                            0);
                }
                if (popupWindowset != null && !popupWindowset.isShowing()) {
                    popupWindowset.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                } else {
                    showPopuWindow(view);
                }
                break;
            case R.id.authersay_creat:
                Intent intent = new Intent(ArticleActivity.this, AuthorSayActivity.class);
                intent.putExtra("authorsay", authorSay);
                startActivityForResult(intent, 10);
                break;
            case R.id.toleft:

                if (textPosition > 0) {
                    isnochange = true;
                    textPosition = textPosition - 1;
                    zhangjietext.setText(textList.get(textPosition));
                    zhangjietext.setSelection(zhangjietext.getText().length());
                    toleftorright();
                }
                break;
            case R.id.toright:

                if (textList.size() > textPosition + 1) {
                    isnochange = true;
                    textPosition++;
                    zhangjietext.setText(textList.get(textPosition));
                    zhangjietext.setSelection(zhangjietext.getText().length());
                    toleftorright();
                }
                break;
        }
    }

    //iscungao:true是存稿，false是发布
    private void isCungao(final boolean iscungao) {
        if (!UserManageBean.isLogin(ArticleActivity.this)) {
            return;
        }
        if (!iscungao) {
            if (volume0k.getText().toString().equals("")) {
                showToast("请选择或创建卷");
            } else if (zhangjiename.getText().toString().equals("")) {
                showToast("章节名不能为空");
            } else if (StringTool.isEmpty(zhangjietext.getText().toString())) {
                showToast("章节内容不能为空");
            } else if (zhangjietext.getText().toString().length() < 10) {
                showToast("章节内容不能少于十个字哦！");
            } else {
                CreadChapterBookBean creadChapterBookBean = new CreadChapterBookBean();
                if (isCaogaoCome == 1) {
                    creadChapterBookBean.setId(String.valueOf(bookDataBean.getId()));
                }
                creadChapterBookBean.setBookisvip(isvip);
                creadChapterBookBean.setBookId(bookId);
                creadChapterBookBean.setBookTitle(bookName);
                creadChapterBookBean.setVolumeId(volumId);
                creadChapterBookBean.setChapterTitle(zhangjiename.getText().toString());
                creadChapterBookBean.setChapterContent(zhangjietext.getText().toString());
                creadChapterBookBean.setAuthorWords(StringTool.getAuthorsayText(authorSay));
                creadChapterBookBean.setIsCaogao(isCaogaoCome);
                creadChapterBookBean.setReleastime(0);
                creadChapterBookBean.setWhereCome(0);
                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent1.putExtra("bookBean", creadChapterBookBean);
                startActivityForResult(intent1, 2);
            }
        } else {
            toCungaoDIalog();
        }

    }

    private void toCungaoDIalog() {
        if (tocunDialog == null) {
            tocunDialog = new TocunDialog(this);
            tocunDialog.setListener(new TocunDialog.Listener() {
                @Override
                public void back() {
                    goBack();
                }

                @Override
                public void cuntocungao() {
                    toCungao();
                }
            }, "尚未保存，是否保存后退出？", "直接退出", "保存并退出");
        }
        tocunDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!StringTool.isEmpty(zhangjietext.getText().toString())) {
                if (volumId.equals("0")) {
                    showToast("请重新选择卷");
                    return true;
                }

                isCungao(true);
            } else {
                CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                goBack();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //存稿type ：1是从草稿箱过来
    private void toCungao() {
        if (!UserManageBean.isLogin(ArticleActivity.this)) {
            return;
        }
        String chapter;
        String chapterName;
        chapter = StringTool.getChapterText(zhangjietext.getText().toString());
        chapterName = StringTool.isEmpty(zhangjiename.getText().toString()) ? "无章节名称" : zhangjiename.getText().toString();
        if (isCaogaoCome == 1) {
            OkHttpUtils.post(HttpManager.IP + "/chapter-update")
                    .params("chapterTitle", chapterName)
                    .params("bookId", bookId)
                    .params("bookWriterId", UserManageBean.userBean.getUserId())
                    .params("chapterContent", chapter)
                    .params("releaseTime", TimeTool.getThistime())
                    .params("chapterLength", StringTool.getChapterTextLength(zhangjietext.getText().toString()))
                    .params("volumeId", volumId)
                    .params("whetherPublic", "1")
                    .params("id", String.valueOf(bookDataBean.getId()))
                    .params("authorWords", StringTool.getAuthorsayText(authorSay))
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (noBackgLodDialog == null) {
                                noBackgLodDialog = new NoBackgLodDialog(ArticleActivity.this, true);
                            }
                            noBackgLodDialog.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            noBackgLodDialog.dismis();
                            try {
                                JSONObject js = new JSONObject(s);
                                if (js.getInt("returnCode") == 200) {
                                    showToast(js.getString("msg"));
                                    CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                                    goBack();
                                } else if (js.getInt("returnCode") == 400) {
                                    Intent intent3 = new Intent(ArticleActivity.this, LoginActivity.class);
                                    startActivity(intent3);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                goBack();
                            }
                        }
                    });
        } else {
            OkHttpUtils.post(HttpManager.IP + "/chapter-creates")

                    .params("bookId", bookId)
                    .params("bookWriterId", String.valueOf(UserManageBean.userBean.getUserId()))
                    .params("bookTitle", bookName)
                    .params("chapterTitle", chapterName)
                    .params("chapterContent", chapter)
                    .params("releaseTime", TimeTool.getThistime())
                    .params("chapterIsvip", String.valueOf(vip))
                    .params("volumeId", volumId)
                    .params("whetherPublic", "1")
                    .params("chapterLength", StringTool.getChapterTextLength(chapter))
                    .params("authorWords", StringTool.getAuthorsayText(authorSay))
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (noBackgLodDialog == null) {
                                noBackgLodDialog = new NoBackgLodDialog(ArticleActivity.this, true);
                            }
                            noBackgLodDialog.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            noBackgLodDialog.dismis();
                            try {
                                JSONObject js = new JSONObject(s);
                                if (js.getInt("returnCode") == 200) {
                                    showToast(js.getString("msg"));
                                    CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                                    goBack();
                                } else if (js.getInt("returnCode") == 400) {
                                    Intent intent3 = new Intent(ArticleActivity.this, LoginActivity.class);
                                    startActivity(intent3);
                                } else {
                                    showToast(js.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }

    }


    private BaseQuickAdapter adapterSet;

    private void showPopuWindow(View view) {
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(this).inflate(R.layout.creatset, null);
        popupWindowset = new PopupWindow(contentView);
        viewHolder = new ViewHolder(contentView);
        viewHolder.creatSetRecycle.setAdapter(adapterSet = new BaseQuickAdapter<Integer, BaseViewHolder>(R.layout.creat_backitem, beijingBean.getBeijinglist()) {
            @Override
            protected void convert(BaseViewHolder helper, Integer item) {
                AutoUtils.autoSize(helper.itemView);
                if (helper.getLayoutPosition() == beijingposition) {
                    ((ImageView) helper.getView(R.id.creat_recycle_image)).setImageResource(beijingBean.getBeijingselectlist().get(beijingposition));
                } else {
                    ((ImageView) helper.getView(R.id.creat_recycle_image)).setImageResource(beijingBean.getBeijinglist().get(helper.getLayoutPosition()));
                }
            }
        });
        viewHolder.creatSetRecycle.setLayoutManager(new GridLayoutManager(ArticleActivity.this, 5));
        adapterSet.setOnItemClickListener((adapter, view5, position) -> {
            CreatChapterSettingManager.getInstance().saveCreatBeijingcolor(position);
            beijingposition = position;
            adapterSet.notifyDataSetChanged();
            isNeight = 0;
            CreatChapterSettingManager.getInstance().saveIsCreatNightDay(isNeight);
            viewHolder.isnighttext.setText("黑夜");
            viewHolder.isnightimage.setImageResource(R.mipmap.night);
            setBeijingAll();
        });
        viewHolder.creatSetSun.setProgress(seekposition);
        viewHolder.creatSetSun.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ScreenUtils.setScreenBrightness(progress, ArticleActivity.this);
                seekposition = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                CreatChapterSettingManager.getInstance().saveCreatSeekPosition(seekposition);
            }
        });
        viewHolder.creatSetSize.setProgress(zitiposition);
        viewHolder.creatSetSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                zitiposition = progress;
                zhangjietext.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12 + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                CreatChapterSettingManager.getInstance().saveCreatZitidaxiao(zitiposition);
            }
        });
        if (isNeight == 1) {
            viewHolder.isnighttext.setText("白天");
            viewHolder.isnightimage.setImageResource(R.mipmap.creatimage_sun);
        } else {
            viewHolder.isnighttext.setText("黑夜");
            viewHolder.isnightimage.setImageResource(R.mipmap.night);
        }
        viewHolder.linearLayout.setOnClickListener(v -> {
            if (isNeight == 0) {
                isNeight = 1;
                viewHolder.isnighttext.setText("白天");
                viewHolder.isnightimage.setImageResource(R.mipmap.creatimage_sun);
            } else {
                isNeight = 0;
                viewHolder.isnighttext.setText("黑夜");
                viewHolder.isnightimage.setImageResource(R.mipmap.night);
            }
            CreatChapterSettingManager.getInstance().saveIsCreatNightDay(isNeight);
            setBeijingAll();
        });
        //使其聚集
        popupWindowset.setFocusable(true);
        // 设置允许在外点击消失
        popupWindowset.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindowset.setBackgroundDrawable(new BitmapDrawable(getResources()));
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindowset.setWidth(ScreenUtils.getScreenWidth());
        popupWindowset.setHeight(ScreenUtils.getScreenHeight() / 4);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindowset.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindowset.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void setBeijingAll() {
        if (isNeight == 1) {
            creatTop.setBackgroundResource(R.mipmap.top_neight);//导航栏
            setCreat.setImageResource(beijingBean.getSetlist().get(0));//设置
            yijianpaiban.setImageResource(beijingBean.getOnekeylist().get(0));//一键排版
            yijianbaocun.setImageResource(beijingBean.getSavelist().get(0));
            view1.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(0)));//分割线
            view2.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(0)));//分割线
            view3.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(0)));//分割线
            view4.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(0)));//分割线
            backArticle.setImageResource(beijingBean.getBackimagelist().get(0));//返回
            textnumArticle.setTextColor(Color.parseColor(beijingBean.getTopziticolort().get(0)));//顶部字数
            okArticle.setTextColor(Color.parseColor(beijingBean.getTopziticolort().get(0)));//发布
            volume0k.setTextColor(Color.parseColor("#798795"));//卷名
            zhangjiename.setTextColor(Color.parseColor("#798795"));//章节名
            zhangjietext.setTextColor(Color.parseColor("#798795"));//内容
            auhorSayText.setTextColor(Color.parseColor("#ffffff"));//作者的话
            auhorSayAddimage.setImageResource(R.mipmap.authoraddwright);
            authersayCreat.setCardBackgroundColor(Color.parseColor("#3d3d3d"));

            backBgImage.setImageResource(R.mipmap.back_night);//背景
        } else {
            creatTop.setBackgroundResource(beijingBean.getToplist().get(beijingposition));//导航栏
            setCreat.setImageResource(beijingBean.getSetlist().get(beijingposition));//设置
            yijianpaiban.setImageResource(beijingBean.getOnekeylist().get(beijingposition));//一键排版
            yijianbaocun.setImageResource(beijingBean.getSavelist().get(beijingposition));
            view1.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(beijingposition)));//分割线
            view2.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(beijingposition)));//分割线
            view3.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(beijingposition)));//分割线
            view4.setBackgroundColor(Color.parseColor(beijingBean.getFengexiancolort().get(beijingposition)));//分割线
            backArticle.setImageResource(beijingBean.getBackimagelist().get(beijingposition));//返回
            textnumArticle.setTextColor(Color.parseColor(beijingBean.getTopziticolort().get(beijingposition)));//顶部字数
            okArticle.setTextColor(Color.parseColor(beijingBean.getTopziticolort().get(beijingposition)));//发布
            volume0k.setTextColor(Color.parseColor(beijingBean.getZiticolort().get(beijingposition)));//卷名
            zhangjiename.setTextColor(Color.parseColor(beijingBean.getZiticolort().get(beijingposition)));//章节名
            zhangjietext.setTextColor(Color.parseColor(beijingBean.getZiticolort().get(beijingposition)));//内容
            auhorSayText.setTextColor(Color.parseColor("#f77583"));//作者的话
            auhorSayAddimage.setImageResource(R.mipmap.authoradd);
            authersayCreat.setCardBackgroundColor(Color.parseColor("#ffffff"));
            backBgImage.setImageResource(beijingBean.getBeijingbglist().get(beijingposition));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            volumId = data.getStringExtra("volumId");
            volumName = data.getStringExtra("volumName");
            volume0k.setText(volumName);
        }
        if (requestCode == 2 && resultCode == 2) {
            goBack();
        }
        if (requestCode == 10 && resultCode == 10) {
            authorSay = data.getStringExtra("authorsay");
        }
    }

    class ViewHolder {
        @BindView(R.id.creat_set_sun)
        SeekBar creatSetSun;
        @BindView(R.id.creat_set_size)
        SeekBar creatSetSize;
        @BindView(R.id.creat_set_recycle)
        RecyclerView creatSetRecycle;
        @BindView(R.id.isornight)
        LinearLayout linearLayout;
        @BindView(R.id.isnighttext)
        TextView isnighttext;
        @BindView(R.id.isnightimage)
        ImageView isnightimage;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }


}
